<?php

namespace App\Utils;

class StringUtil
{
    const TYPE_NUMBER = 1;
    const TYPE_LETTER = 2;
    const TYPE_MIXED = 3;

    /**
     * 生成随机字符串
     * @param int $length 长度
     * @param int $type 类型：1纯数字，2纯字母，3数字字母混合
     * @return string
     */
    public static function random(int $length = 6, int $type = self::TYPE_NUMBER): string
    {
        $numbers = '0123456789';
        $letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

        switch ($type) {
            case self::TYPE_NUMBER:
                $chars = $numbers;
                break;
            case self::TYPE_LETTER:
                $chars = $letters;
                break;
            default:
                $chars = $numbers . $letters;
        }

        $result = '';
        $max = strlen($chars) - 1;
        for ($i = 0; $i < $length; $i++) {
            $result .= $chars[mt_rand(0, $max)];
        }

        return $result;
    }

    /**
     * 获取年龄
     * @param int $birthday 生日
     * @return int
     */
    public static function getAge(int $birthday): int
    {
        $age = floor((time() - $birthday) / 31536000); // 31536000 = 365 * 24 * 60 * 60
        if ($age <= 0) {
            $age = 1;
        }
        return $age;
    }

    /**
     * 加密姓名（显示首尾字符，中间用*代替）
     * @param string $name 姓名
     * @return string
     */
    public static function maskName(string $name): string
    {
        if (empty($name)) {
            return '';
        }
        
        $len = mb_strlen($name);
        if ($len > 2) {
            return mb_substr($name, 0, 1) . 
                str_repeat('*', $len - 2) . 
                mb_substr($name, -1);
        }
        return mb_substr($name, 0, 1) . '*';
    }

    /**
     * 加密手机号（保留前3后4，中间用*代替）
     * @param string $phone 手机号
     * @return string
     */
    public static function maskPhone(string $phone): string
    {
        if (empty($phone)) {
            return '';
        }
        return substr_replace($phone, '****', 3, -4);
    }
}